<script setup lang="ts">

import { onMounted, onUnmounted, ref, watch } from 'vue'
import { type ECharts, init } from 'echarts'
import type { Rank } from '@/types/eCommerce'

const props = defineProps<{
  rankData: Rank[]
}>()
const echarts_ref = ref<HTMLDivElement>()

let myEcharts: ECharts

const initEcharts = () => {
  myEcharts = init(echarts_ref.value as HTMLDivElement)
  const initOption = {
    title: {
      text: '各省份销量',
      top: '2%',
      left: '2%'
    },
    grid: {
      top: '15%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 0
      }
    },
    axisTick: {
      length: 10
    },
    yAxis: {
      type: 'value'
    },
    series: {
      type: 'bar'
    }
  }
  myEcharts.setOption(initOption, true)
}
const dataEcharts = (index: number = 1) => {
  const xAxios: string[] = []
  const series: number[] = []
  for (let i = (index - 1) * 10; i < index * 10; i++) {
    xAxios.push(props.rankData[i].name)
    series.push(props.rankData[i].value)
  }
  const dataOption = {
    xAxis: {
      data: xAxios
    },
    series: [{
      data: series
    }]
  }
  myEcharts.setOption(dataOption)
}
const adapterEcharts = () => {
  const width = echarts_ref.value!.offsetWidth
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: width / 100 * 2.5
      }
    },
    series: [{
      barWidth: width / 100 * 5
    }]
  }
  myEcharts.setOption(adapterOption)
  myEcharts.resize()
}


const loading = ref(true)
watch(props, () => {
  dataEcharts()
  setTimeout(() => {
    loading.value = false
  }, 300)
})
onMounted(() => {
  initEcharts()
  adapterEcharts()
  window.addEventListener('resize', adapterEcharts)
})

onUnmounted(() => {
  window.removeEventListener('resize', adapterEcharts)
})
</script>

<template>
  <div v-loading="loading" class="echarts">
    <div ref="echarts_ref" class="echartsDom"></div>
  </div>
</template>

<style lang="css" scoped>
@import "@/assets/style/componentsEcharts.css";
</style>